<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <FullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <PageForm
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-assetName>
                <el-input
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择资产"
                  v-model="formInfo.data.assetName"
                >
                  <template #append>
                    <el-icon @click="addAsset"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </PageForm>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="'费用支出明细信息'" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-remove>
                <el-button :disabled="!canRemove" @click="remove"
                  >删除产品</el-button
                >
              </template>
              <template v-slot:filter-batchHandleApplyDeptName>
                <el-input
                  v-model="filterInfo.data.applyDeptName"
                  type="input"
                  style="width: 180px"
                  :disabled="true"
                  :class="'not-mongolia'"
                  placeholder="请选择申请部门"
                >
                  <template #append>
                    <el-icon @click="openApplyDeptWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
                <el-button @click="batchHandle('applyDeptName')"
                  >申请部门设置</el-button
                >
              </template>
              <template v-slot:filter-batchHandleApplyDoctor>
                <el-input
                  v-model="filterInfo.data.applyDoctor"
                  type="input"
                  style="width: 180px"
                  placeholder="请输入开单医生"
                  :maxlength="30"
                ></el-input>
                <el-button @click="batchHandle('applyDoctor')"
                  >开单医生设置</el-button
                >
              </template>
              <template v-slot:filter-batchHandleExecuteDeptName>
                <el-input
                  v-model="filterInfo.data.executeDeptName"
                  type="input"
                  style="width: 180px"
                  :disabled="true"
                  :class="'not-mongolia'"
                  placeholder="请选择执行部门"
                >
                  <template #append>
                    <el-icon @click="openExecuteDeptWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
                <el-button @click="batchHandle('executeDeptName')"
                  >执行部门设置</el-button
                >
              </template>
              <template v-slot:filter-batchHandleExecuteDoctor>
                <el-input
                  v-model="filterInfo.data.executeDoctor"
                  type="input"
                  style="width: 180px"
                  placeholder="请输入执行医生"
                  :maxlength="30"
                ></el-input>
                <el-button @click="batchHandle('executeDoctor')"
                  >执行医生设置</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :isDynamic="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  row-key="uuid"
                  @handleEvent="handleEvent"
                  @changeValidate="changeValidate"
                >
                  <template v-slot:col-applyDeptName="scope">
                    <el-input
                      v-model="scope.row.applyDeptName"
                      type="input"
                      :disabled="true"
                      :class="'not-mongolia'"
                      placeholder="请选择申请部门"
                    >
                      <template #append>
                        <el-icon @click="openApplyDeptWindow(scope.$index)"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </template>
                  <template v-slot:col-executeDeptName="scope">
                    <el-input
                      v-model="scope.row.executeDeptName"
                      type="input"
                      :disabled="true"
                      :class="'not-mongolia'"
                      placeholder="请选择执行部门"
                    >
                      <template #append>
                        <el-icon @click="openExecuteDeptWindow(scope.$index)"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </FullScreen>
    </div>
    <!-- 添加资产 -->
    <SelectAssetAnalysis
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query"
      :check-box="false"
      :highlightRow="true"
      @callback="callBackAsset"
    />
    <select-dept
      v-if="selectApplyDeptInfo.visible"
      v-model:show-dialog="selectApplyDeptInfo.visible"
      :query="selectApplyDeptInfo.query"
      :check-box="false"
      :highlight-row="true"
      :saveEmpty="true"
      @callback="selectApplyDeptCallback"
    />
    <select-dept
      v-if="selectExecuteDeptInfo.visible"
      v-model:show-dialog="selectExecuteDeptInfo.visible"
      :query="selectExecuteDeptInfo.query"
      :check-box="false"
      :highlight-row="true"
      :saveEmpty="true"
      @callback="selectExecuteDeptCallback"
    />
  </div>
</template>

<script setup name="AssetTransferModify">
import {
  batchInsertIncomeCostDetail,
  updateIncomeCostDetail,
  getIncomeCostDetailById,
  getAssetCostConfigByAssetId,
} from '@/api/asset'

const props = defineProps(['visible', 'title', 'orderId'])
const { proxy } = getCurrentInstance()
const emits = defineEmits()
//表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '资产名称',
      value: 'assetName',
      type: 'slot',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'input',
      disabled: true,
    },
    {
      label: '规格',
      value: 'standard',
      type: 'input',
      disabled: true,
    },
    { label: '厂家', value: 'brandName', type: 'input', disabled: true },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'input',
      disabled: true,
    },
    {
      label: '仓库',
      value: 'depotName',
      type: 'input',
      disabled: true,
    },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '管理部门',
      value: 'manageDeptName',
      type: 'input',
      disabled: true,
    },
    { label: '位置', value: 'location', type: 'input', disabled: true },
  ],
  rules: {
    assetName: [
      {
        required: true,
        message: '请输入资产名称',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  data: {
    applyDeptId: '',
    applyDeptName: '',
    applyDoctor: '',
    executeDeptId: '',
    executeDeptName: '',
    executeDoctor: '',
  },
  list: [
    {
      type: 'slot',
      label: '删除产品',
      value: 'remove',
      show: props.orderId ? false : true,
    },
    {
      type: 'slot',
      label: '一键设置',
      value: 'batchHandleApplyDeptName',
    },
    { type: 'slot', label: '一键设置', value: 'batchHandleApplyDoctor' },
    { type: 'slot', label: '一键设置', value: 'batchHandleExecuteDeptName' },
    { type: 'slot', label: '一键设置', value: 'batchHandleExecuteDoctor' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [{ businessDate: '', uuid: proxy.$fn.getUid() }],
  selections: [],
  fieldList: [],
  fieldList1: [
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      TimePickerOptions: {
        disabledDate(time) {
          // 大于当前的时间都不能选 (+十分钟让点击此刻的时候可以选择到当前时间)
          return time.getTime() > +new Date() + 1000 * 600 * 1
        },
      },
      width: '180px',
      rules: [
        {
          required: true,
          message: '请选择业务日期',
          trigger: ['change', 'blur'],
        },
      ],
      disabled: props.orderId ? true : false,
    },
    {
      label: '申请部门',
      value: 'applyDeptName',
      type: 'slot',
      width: '180px',
    },
    {
      label: '开单医生',
      value: 'applyDoctor',
      type: 'input',
      width: '180px',
      maxlength: 30,
    },
    {
      label: '执行部门',
      value: 'executeDeptName',
      type: 'slot',
      width: '180px',
    },
    {
      label: '执行医生',
      value: 'executeDoctor',
      type: 'input',
      width: '180px',
      maxlength: 30,
    },
    {
      label: '检查(治疗)人次',
      value: 'treatPersonTime',
      type: 'number',
      max: 999999999999999,
      width: '180px',
      rules: [
        {
          validator: proxy.$validate.naturalnumberNo,
          trigger: ['blur', 'change'],
        },
      ],
    },
    {
      label: '阳性人次',
      value: 'positivePersonTime',
      type: 'number',
      max: 999999999999999,
      width: '180px',
      rules: [
        {
          validator: proxy.$validate.naturalnumberNo,
          trigger: ['blur', 'change'],
        },
      ],
    },
    {
      label: '收入金额(元)',
      value: 'incomeAmount',
      type: 'number',
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
      max: 999999999999999,
      width: '180px',
      rules: [
        {
          validator: proxy.$validate.positiveMoneyNoAsset,
          trigger: ['blur', 'change'],
        },
      ],
    },
  ],
  fieldList2: [
    {
      label: '开机时长(h)',
      value: 'powerUpTime',
      type: 'number',
      max: 999999999999999,
      width: '180px',
      rules: [
        {
          validator: proxy.$validate.naturalnumberNo,
          trigger: ['blur', 'change'],
        },
      ],
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '新增行',
        event: add,
        show: props.orderId ? false : true,
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: props.orderId ? false : true,
      },
    ],
  },
})
const selectAssetInfo = ref({
  visible: false,
  query: {},
})
const selectApplyDeptInfo = ref({
  visible: false,
  query: {
    // deptAuth: 'id',
  },
})
const selectExecuteDeptInfo = ref({
  visible: false,
  query: {
    // deptAuth: 'id',
  },
})
const costFieldList = ref([])
const costConfig = ref([])
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    emits('update:visible', val) // 更新父组件visible
  },
})
const canRemove = computed(() => {
  return tableInfo.value.selections.length
})
function getCostFieldList() {
  //获取支出项目字段
  tableInfo.value.fieldList = tableInfo.value.fieldList1.concat(
    tableInfo.value.fieldList2
  )
  let asset_cost_project =
    proxy.$store.state.permission.dict['asset_cost_project']
  if (asset_cost_project && asset_cost_project.length) {
    let fieldList = []
    asset_cost_project.map((item) => {
      if (item.isEnable === 1) {
        let obj = {
          label: item.name + '(元)',
          value: item.code,
          type: 'number',
          precision:
            proxy.$store.state.permission.systemConfig.assets_price_precision,
          max: 999999999999999,
          width: '180px',
          rules: [
            {
              validator: proxy.$validate.positiveMoneyNoAsset,
              trigger: ['blur', 'change'],
            },
          ],
          disabled: false,
        }
        fieldList.push(obj)
      }
    })
    costFieldList.value = fieldList
    tableInfo.value.fieldList = tableInfo.value.fieldList1.concat(
      fieldList,
      tableInfo.value.fieldList2
    )
  }
}

function getMain() {
  getIncomeCostDetailById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data
      let assetCostDetailVOList = res.data.assetCostDetailVOList
      let obj = formInfo.value.data
      if (assetCostDetailVOList && assetCostDetailVOList.length) {
        assetCostDetailVOList.forEach((el) => {
          obj[el.costProject] = el.amount
          obj.uuid = proxy.$fn.getUid()
        })
      }
      tableInfo.value.data = [obj] || [
        { businessDate: '', uuid: proxy.$fn.getUid() },
      ]
      getCostConfig()
    }
  })
}
function changeValidate(str) {
  setTimeout(() => {
    proxy.$refs['tableForm'].clearValidate(str)
  }, 30)
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function handleEvent(str, e, row, index, fieldValue) {
  if (str === 'changeNumber' && fieldValue === 'treatPersonTime') {
    costConfig.value.forEach((item) => {
      if (item.calcRule === 0) {
        tableInfo.value.data[index][item.costProject] = proxy.$fn.accMul(
          e || 0,
          item.costAmount || 0
        )
      } else if (item.calcRule === 1) {
        tableInfo.value.data[index][item.costProject] = 0
      }
    })
  } else if (str === 'tableCheck') {
    tableInfo.value.selections = e
  }
}
function disabledFieldListItem(enable, nameValue) {
  if (tableInfo.value.fieldList && tableInfo.value.fieldList.length) {
    tableInfo.value.fieldList.forEach((item) => {
      if (nameValue === item.value) {
        item.disabled = enable
      }
    })
  }
}
function getCostConfig() {
  //若系统配置了按人次计算的支出项，输入人次后自动根据人次计算出支出费用
  if (formInfo.value.data.assetId && formInfo.value.data.assetId !== -2) {
    getAssetCostConfigByAssetId(formInfo.value.data.assetId).then((res) => {
      if (res && res.success) {
        let data =
          res.data && res.data.details && res.data.details.length
            ? res.data.details
            : []
        costConfig.value = data
        costFieldList.value.forEach((item) => {
          disabledFieldListItem(false, item.value)
        })
        data.forEach((item) => {
          disabledFieldListItem(true, item.costProject)
          if (item.calcRule === 1) {
            tableInfo.value.data.forEach((el) => {
              el[item.costProject] = 0
            })
          }
        })
      }
    })
  }
}
function save() {
  let filedObj = {}
  costFieldList.value.forEach((item) => {
    filedObj[item.value] = undefined
  })
  let sumFlag = false
  if (tableInfo.value.data && tableInfo.value.data.length) {
    tableInfo.value.data.forEach((item) => {
      let sum = 0
      for (let key in filedObj) {
        sum = proxy.$fn.accAdd(sum, item[key] || 0)
      }
      sum = proxy.$fn.accAdd(sum, item.treatPersonTime || 0)
      sum = proxy.$fn.accAdd(sum, item.positivePersonTime || 0)
      sum = proxy.$fn.accAdd(sum, item.incomeAmount || 0)
      sum = proxy.$fn.accAdd(sum, item.powerUpTime || 0)
      if (sum === 0) {
        sumFlag = true
      }
    })
  }
  if (sumFlag) {
    proxy.$message.warning('明细各行至少有一项数据得大于0！')
    return
  }
  let formRefs = [formInfo.value.ref, proxy.$refs.tableForm]
  proxy.$fn.checkForm(formRefs).then(() => {
    let costMap = {}
    costFieldList.value.forEach((item) => {
      costMap[item.value] = undefined
    })
    let assetCostDetailVOList = tableInfo.value.data.map((item) => {
      item.assetId = formInfo.value.data.assetId
      item.sourceType = 1
      let obj = {}
      for (let key in costMap) {
        obj[key] = item[key] || 0
      }
      item.costMap = obj
      return item
    })
    if (props.orderId) {
      updateIncomeCostDetail(assetCostDetailVOList[0]).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          emits('returnModify', false)
        }
      })
    } else {
      batchInsertIncomeCostDetail(assetCostDetailVOList).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          emits('returnModify', false)
        }
      })
    }
  })
}

//选择资产
function addAsset() {
  selectAssetInfo.value.visible = true
}
function callBackAsset(data) {
  if (data && data.id) {
    formInfo.value.data['assetCode'] = data.assetCode
    formInfo.value.data['assetName'] = data.assetName
    formInfo.value.data['standard'] = data.standard
    formInfo.value.data['brandName'] = data.brandName
    formInfo.value.data['supplierId'] = data.supplierId
    formInfo.value.data['supplierName'] = data.supplierName
    formInfo.value.data['depotName'] = data.depotName
    formInfo.value.data['depotId'] = data.depotId
    formInfo.value.data['useDeptName'] = data.useDeptName
    formInfo.value.data['useDeptId'] = data.useDeptId
    formInfo.value.data['manageDeptName'] = data.manageDeptName
    formInfo.value.data['manageDeptId'] = data.manageDeptId
    formInfo.value.data['location'] = data.location
    formInfo.value.data['assetId'] = data.assetId
  } else {
    formInfo.value.data['assetCode'] = ''
    formInfo.value.data['assetName'] = ''
    formInfo.value.data['standard'] = ''
    formInfo.value.data['brandName'] = ''
    formInfo.value.data['supplierId'] = ''
    formInfo.value.data['supplierName'] = ''
    formInfo.value.data['depotName'] = ''
    formInfo.value.data['depotId'] = ''
    formInfo.value.data['useDeptName'] = ''
    formInfo.value.data['useDeptId'] = ''
    formInfo.value.data['manageDeptName'] = ''
    formInfo.value.data['manageDeptId'] = ''
    formInfo.value.data['location'] = ''
    formInfo.value.data['assetId'] = ''
  }
  tableInfo.value.data = [{ businessDate: '', uuid: proxy.$fn.getUid() }]
  getCostConfig()
}
//删除
function remove(selectRow = undefined) {
  if (tableInfo.value.data.length <= 1) {
    proxy.$message.warning('费用支出明细中至少保留一条数据')
    return
  }
  if (selectRow && selectRow.uuid) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => !tableInfo.value.selections.includes(row)
    )
  }
}
function add() {
  //新增行
  tableInfo.value.data.push({ businessDate: '', uuid: proxy.$fn.getUid() })
}
function openApplyDeptWindow(index = undefined) {
  if (typeof index === 'number') {
    selectApplyDeptInfo.value.index = index
  } else {
    selectApplyDeptInfo.value.index = undefined
  }
  selectApplyDeptInfo.value.visible = true
}
function selectApplyDeptCallback(row) {
  if (
    selectApplyDeptInfo.value.index ||
    selectApplyDeptInfo.value.index === 0
  ) {
    if (row) {
      tableInfo.value.data[selectApplyDeptInfo.value.index].applyDeptId = row.id
      tableInfo.value.data[selectApplyDeptInfo.value.index].applyDeptName =
        row.name
    } else {
      tableInfo.value.data[selectApplyDeptInfo.value.index].applyDeptId = '.'
      tableInfo.value.data[selectApplyDeptInfo.value.index].applyDeptName = ''
    }
  } else {
    if (row) {
      filterInfo.value.data.applyDeptId = row.id
      filterInfo.value.data.applyDeptName = row.name
    } else {
      filterInfo.value.data.applyDeptId = '.'
      filterInfo.value.data.applyDeptName = ''
    }
  }
}
function openExecuteDeptWindow(index = undefined) {
  if (typeof index === 'number') {
    selectExecuteDeptInfo.value.index = index
  } else {
    selectExecuteDeptInfo.value.index = undefined
  }
  selectExecuteDeptInfo.value.visible = true
}
function selectExecuteDeptCallback(row) {
  if (
    selectExecuteDeptInfo.value.index ||
    selectExecuteDeptInfo.value.index === 0
  ) {
    if (row) {
      tableInfo.value.data[selectExecuteDeptInfo.value.index].executeDeptId =
        row.id
      tableInfo.value.data[selectExecuteDeptInfo.value.index].executeDeptName =
        row.name
    } else {
      tableInfo.value.data[selectExecuteDeptInfo.value.index].executeDeptId =
        '.'
      tableInfo.value.data[selectExecuteDeptInfo.value.index].executeDeptName =
        ''
    }
  } else {
    if (row) {
      filterInfo.value.data.executeDeptId = row.id
      filterInfo.value.data.executeDeptName = row.name
    } else {
      filterInfo.value.data.executeDeptId = '.'
      filterInfo.value.data.executeDeptName = ''
    }
  }
}
function batchHandle(str) {
  //一键设置
  if (tableInfo.value.selections.length) {
    tableInfo.value.selections.forEach((item) => {
      if (str === 'applyDeptName') {
        item.applyDeptId = filterInfo.value.data.applyDeptId
        item.applyDeptName = filterInfo.value.data.applyDeptName
      } else if (str === 'applyDoctor') {
        item.applyDoctor = filterInfo.value.data.applyDoctor
      } else if (str === 'executeDeptName') {
        item.executeDeptId = filterInfo.value.data.executeDeptId
        item.executeDeptName = filterInfo.value.data.executeDeptName
      } else if (str === 'executeDoctor') {
        item.executeDoctor = filterInfo.value.data.executeDoctor
      }
    })
  } else {
    proxy.$message.warning('请勾选数据行')
  }
}
onMounted(() => {
  getCostFieldList()
  if (props.orderId) {
    getMain()
  }
})
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow: hidden;
}
.i-more-disabled {
  cursor: not-allowed;
}
.i-more {
  background-color: #ffffff;
  cursor: pointer;
  height: 26px;
}
</style>
